import sys
import os

sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from config import result_bucket
from aws_model.athena_submit import submit
from sql_lambda.delete import delete_data
from base_class.inspect_logging import print_to_log
import datetime
import json
from aws_model.aws_stepfunc import send_task_success, send_task_failure


def result_cppjsmgzsjc(event):
    date = event.get('p_date')
    if not date:
        date = datetime.datetime.today().strftime('%Y-%m-%d')
    table_name = sys._getframe().f_code.co_name
    delete_data(result_bucket,table_name, date)
    sql = f'''insert into fridge_biz_result.result_cppjsmgzsjc
                (
                   select
                       if(model is null,'',model) as model,sn,fault_content,
                       date_diff('day',buy_time,first_time) as day_diff,
                       format_datetime(current_date - interval '1' month, 'YYYY-MM') as time
                    from
                    (
                        select
                            upper(if(t2.model is null,regexp_extract(t1.zzfld000036,'[a-zA-Z0-9]+-[a-zA-Z0-9]+'),t2.model)) as model,
                            t1.sn,
                            date_parse(
                                concat(
                                    substr(createdat,1,4),'-',
                                    substr(createdat,5,2),'-',
                                    substr(createdat,7,2),' ',
                                    substr(createdat,9,2),':',
                                    substr(createdat,11,2),':',
                                    substr(createdat,13,2)
                                    ),'%Y-%m-%d %H:%i:%S'
                            )  as first_time,
                            date_parse(buy_time,'%Y%m%d') as buy_time,
                            fault_content
                        from
                            (
                             select
                                zzfld00000b as sn ,
                                createdat as createdat,
                                zzfld00002gt as fault_content,
                                zzfld000036,
                                cast(zzfld00002i as varchar) as buy_time,
                                row_number() over(partition by zzfld00000b order by createdat) as rn
                            from
                                ods.kyd_ods
                            where
                                length(zzfld00000b) = 24
                            and
                                zzfld00002ft != '安装'
                            and
                                substr(zzfld00000b,4,7) is not null
                            and
                                zzfld00002i is not null and zzfld00002i <= cast(format_datetime(current_date, 'YYYYMMdd') as int)
                            and
                                substr(zzfld00000b,4,7) != ''
                            and
                                zzfld000001='QT30'
                            and
                                date(p_date) < date('{date}')
                            ) t1
                        left join
                            dim.material t2
                        on
                            substr(t1.sn, 4, 7)=t2.material and t2.type_code = 'FRIDGE'
                        where t1.rn = 1
                    ) t3
                )'''

    athena_response = submit(sql)
    print_to_log("athena_response: ", athena_response)
    output = {"msg": f"{table_name} submit ok", "Payload": {}}
    output = json.dumps(output)
    step_response = send_task_success(tasktoken, output)
    print_to_log("step_response: ", step_response)


if __name__ == '__main__':
    try:
        event = json.loads(sys.argv[1])
        tasktoken = event.get('TaskToken')
        result_cppjsmgzsjc(event)
    except Exception as e:
        print_to_log("athena_submit 失败")
        print_to_log("原因： ", str(e))
        send_task_failure(str(e), f'执行{sys._getframe().f_code.co_filename}错误', tasktoken)

